package com.sqnu.test;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class MyListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        System.out.println("服务器启动 创建spring容器");
        //获取servletContext域对象
        ServletContext servletContext = servletContextEvent.getServletContext();
        //读取spring核心配置文件 创建spring容器对象
        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
        //将容器对象存入servletContext域中
        servletContext.setAttribute("spring",applicationContext);

    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        System.out.println("服务器关闭 关闭spring容器");
        //获取servletContext域对象
        ServletContext servletContext = servletContextEvent.getServletContext();
        //取出spring容器对象
        ClassPathXmlApplicationContext applicationContext  = (ClassPathXmlApplicationContext) servletContext.getAttribute("spring");
        //调用close方法关闭spring容器对象
        applicationContext.close();
    }
}